package com.alibaba.cloud.encry;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;


/**
 * The Class AESUtil.
 *
 * @ClassName: AESUtil
 * @Description: aes 加密算法
 * @author: zhb zhb1316783262@163.com
 * @date: 2018年3月13日 下午5:21:46
 */
public class AESUtil {
    
    /** 解密. */
    private static Cipher cipher;
    /**
     * 密钥
     */
    // private static SecretKey secretKey;
    static {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);// size
            // SecretKey generateKey = keyGenerator.generateKey();
            // byte[] keyBytes = generateKey.getEncoded();
            // secretKey = new SecretKeySpec(keyBytes, "AES");
            cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Encode.
     *
     * @param key the key
     * @param src the src
     * @return the string
     */
    public static String encode(String key, String src) {
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] resultBytes = cipher.doFinal(src.getBytes());
            return Hex.encodeHexString(resultBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Decode.
     *
     * @param key the key
     * @param src the src
     * @return the string
     */
    public static String decode(String key, String src) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = Hex.decodeHex(src.toCharArray());
            return new String(cipher.doFinal(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}